/**
 * Created by hucy on 2016-05-19.
 */
admin.controller('ClassesListCtrl',[
	'$scope',
  '$location',
	'$http',
  '$uibModal',
  'load2scope',
  'removeFromList',
  function($scope,$location,$http,$uibModal,load2scope ,removeFromList){
    load2scope( ['classes' ,'major'] , $scope );
  	$scope.showDetail = function () {
  		var id = $('[name="ids"]:checked').val();
      if(!id) return;
  		$location.path('/detail/classes/'+id);
  	};
    // 删除部门
    $scope.remove = function () {
      var option = {
        $scope : $scope,
        table  : 'classes',
        modalConfig : {
          title:'删除确认',
          content:'您确定要删除该项？<br />\
                  <strong>此操作不可逆！</strong>',
        }
      };
      removeFromList(option);
    }
	}
])
.controller('ClassesDetailCtrl',[
	'$scope',
	'$uibModal',
  '$http',
	'$stateParams',
	'load2scope',
  'localStorageService',
  function($scope,$uibModal,$http,$stateParams,load2scope,localStorageService){
  	var id = $stateParams.id;

  	load2scope(['classes'] , $scope);
    $scope.classesItem = $scope.map.classes[id];

    $scope.update  = true;
    $scope.tempclasses = {};
  	// 切换修改状态
  	$scope.toggleUpdate = function () {

  		if( $scope.update ){
  			// 暂存
  			$.extend($scope.tempclasses,$scope.classesItem);
        console.log('暂存');
      }else{
        $.extend($scope.classesItem,$scope.tempclasses);
        console.log('取消');
      }
      $scope.update = !$scope.update;
    }
    // 修改班级信息
    $scope.modify = function () {
      $http.put('/api/classes/'+$scope.classesItem.id , $scope.classesItem).then(function (data) {
        // console.log(data);
        show_stack('success2');
        $scope.classes[ $scope.classes.indexOf($scope.tempclasses) ] = $scope.classesItem;
        localStorageService.set('classes' , $scope.classes);
        $scope.tempclasses = $scope.classesItem
        $scope.toggleUpdate();

      }, function () {
        console.log('fail');
      });
    }
	}
])

.controller('ClassesAddCtrl', [
  '$scope',
  'localStorageService',
  '$http',
  '$location',

  'load2scope',
  function($scope,localStorageService,$http,$location,load2scope){

    load2scope(['classes' , 'major'] ,$scope);

    $scope.classesItem = {};
    var classesList = $scope.classes;
    var len = classesList.length;
    var id  = parseInt(classesList[len-1].id) + 1;
    console.log( id )
    $scope.classesItem.id = id;

    $scope.add = function () {
      console.log($scope.classesItem)
      $http.post('/api/classes', $scope.classesItem)
        .success(function (data) {
          show_stack('success-add');
          classesList.push($scope.classesItem);
          localStorageService.set('classes' , classesList);
          $location.path('/detail/classes/'+id);
        })
    }
    $scope.back = function () {
      $location.path('/list/classes');
    }
  }
])

